package com.wangyf.thread.c_021_question;

import java.util.ArrayList;
import java.util.List;

/**
 * 写一个题目: 一个线程添加10个元素到容器 另一个线程监听容器 到5个的时候打印后停止
 * Created by feng on 2021/1/16.
 * 使用 wait notify 实现，需要注意 notify不释放锁
 */
public class T03_waitnotify {

    public static void main(String[] args) throws InterruptedException {
        List<Object> list = new ArrayList<>();

        final Object lock = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    list.add(new Object());
                    System.out.println(list.size());
                    if (list.size() == 5) {
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                if (list.size() != 5) {
                    try {
                        lock.wait();
                        System.out.println("t2 end");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
            }
        });

        t2.start();
        Thread.sleep(100);// 确保 t2 先执行 wait 不然有概率t1 先执行 而且直接执行完成
        t1.start();

    }
}
